package com.jcompressor.faces;

/*
 * Copyright (c) 2011, Scott Carnett
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 * following conditions are met:
 * * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 * following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 * following disclaimerin the documentation and/or other materials provided with the distribution.
 * * Neither the name of jcompressor nor the names of its contributors may be used to endorse or promote products
 * derived from this software without specific prior written permission.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.text.StrBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcompressor.JcompressorContext;
import com.jcompressor.config.Configurator;
import com.jcompressor.faces.config.FacesConfigurator;
import com.jcompressor.model.config.Resource;
import com.jcompressor.model.resources.Template;
import com.jcompressor.type.ResourceType;

/**
 * @author Scott Carnett
 */
public class JcompressorServlet extends HttpServlet {
	
	private static final long serialVersionUID = 6054052212540400525L;
	private static final Logger LOGGER = LoggerFactory.getLogger(JcompressorServlet.class);
	
	/**
	 * @see javax.servlet.http.HttpServlet#init(ServletConfig)
	 */
	@Override
	public void init(final ServletConfig servletConfig) throws ServletException {
		super.init(servletConfig);
		LOGGER.debug("Starting Jcompressor...");
		JcompressorContext.init(this.getServletContext(), new FacesConfigurator());
	}
	
	/**
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest, HttpServletResponse)
	 */
	@Override
	protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		final String extension = StringUtils.substringAfterLast(request.getRequestURI(), "/");
		
		final FacesContextBuilder facesContextBuilder = new FacesContextBuilder();
		final FacesContext facesContext = facesContextBuilder.getFacesContext(request, response);
		
		final Configurator configurator = JcompressorContext.getConfigurator();
		final String viewId = (String)facesContext.getExternalContext().getSessionMap().get("JCOMPRESSOR_FACES_VIEW_ID");
		if (configurator.getResourcesConfiguration().containsTemplate(viewId)) {
			final Template template = configurator.getResourcesConfiguration().getTemplate(viewId);
			if (template != null) {
				final List<Resource> newList = new ArrayList<Resource>();
				final List<Resource> resources = template.getResources();
				for (final Resource resource : resources) {
					final Resource res = configurator.getResourcesConfiguration().getResource(resource.getId());
					if (ObjectUtils.equals(res.getType(), ResourceType.resolveByExtension(extension))) {
						newList.add(res);
					}
				}
				
				final StrBuilder builder = new StrBuilder();
				for (final Resource resource : newList) {
					builder.append(resource.getContent());
				}
				
				response.setContentType(ResourceType.resolveByExtension(extension).getContentType());
				
				final PrintWriter out = response.getWriter();
				out.println(builder.toString());
				return;
			}
		}
		
		response.setContentType(ResourceType.resolveByExtension(extension).getContentType());
		
		final PrintWriter out = response.getWriter();
		out.println(StringUtils.EMPTY);
		facesContextBuilder.removeFacesContext();
	}
	
	/**
	 * @see javax.servlet.http.HttpServlet#destroy()
	 */
	@Override
	public void destroy() {}
	
}